//this util doesn't print XML to the console,
//but returns the Document directly by sendRequest()

package utility;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Set;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;

/**
 * This utility function sends XML to eBay and get another XML(Document type)
 * back from eBay.
 */
public class Util_Trading {

	private static final String token = "AgAAAA**AQAAAA**aAAAAA**VP4pTQ**nY+sHZ2PrBmdj6wVnY+sEZ2PrA2dj6wFk4CoAJmGow+dj6x9nY+seQ**Y3IBAA**AAMAAA**4VIeJEk2tIexZ/PMGLr3CGDpY7CweeVJRaq1XimMp1Oxl0iPQsgHyFIFlSKYwlAPqYUiYUc1AY/1I9tjJOAKwrfbTdQqRSgc41XiYWqQK59f2RPPcOXSM2cRdJI3qIHiLU9v3rjcqgpo0sG7zIYw0M+2Amo48E0I2zr8XlKv2VQXg7rLRYZeXj7GnJYOpBg9o9CCQRoBT6kXYyVaKYpGKp/spcq004tHSB8TyhO3EkKsAJcLfmsGsxkWsb5Cxp0Sgn0oOAqYtwfbYIPQ4z+mlfLFi52Bbjem+LrsLgcEyfvksdL+83tqwzmZqrb41Bj0VBXD4aI9fxPdxK6XmObosUu8TtnGRh9X454gFgelqVugYJkqSjlvtiIn86uleNs+Y/Sid77cyyI7Fs2TvoYTQ2+rMMQLyR5iwZgIGoJW4XdDfLCkeyatWqeER7gcGkdQFf+revawSl6TngczvSQx1ZG6O9sgmq5uVE3WF1n1wQijz7qnxOSG39c78tzDpslYOdEfvbUajkDvFmkLBiMgXPRek1B9i73l7sVK6zobz0T8yDhk7Uk8R992zZNJckwF7IwwlxReELapwpcbVrQXy1LKiVxdUDxfV/2ctvoUtqWBY5h4UoHZEOpUjztRy1YwvqaessTcX5hmew8zuDeGWzod2ST4gkPDUg0uWdzhbQr1KEgFSnyrwNHi/Ixx1mesIteksNMG10D5DTQOoWzzglBCIvtCTHOT18qyPm6LABCAg+hUmx8rE5zboJ98jU8c";

	public static Document sendRequest(String template,
			HashMap<String, String> data) {

		try {
			// get the template XML
			URL url = new URL("http://localhost:8080/infinity-task7/template/"
					+ template);
			InputStream in = url.openStream();
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder docBuilder;
			docBuilder = factory.newDocumentBuilder();
			Document xmlDoc = docBuilder.parse(in);
			// replace the token in the template with the real token
			xmlDoc.getElementsByTagName("eBayAuthToken").item(0)
					.getChildNodes().item(0).setNodeValue(token);
			// System.out.println(xmlDoc.getElementsByTagName("eBayAuthToken").item(0)
			// .getChildNodes().item(0).getNodeValue());

			// fill in data field
			if (data != null) {
				Set<String> keys = data.keySet();
				for (String key : keys) {
					xmlDoc.getElementsByTagName(key).item(0).getChildNodes()
							.item(0).setNodeValue(data.get(key));
				}
			}

			
			// xml server
			URL ebay_url = new URL("https://api.sandbox.ebay.com/ws/api.dll");
			URLConnection ebay_con = ebay_url.openConnection();

			// Add header
			// ebay_con.addRequestProperty("Content-Type", "text/xml");
			// ebay_con.addRequestProperty("X-EBAY-SOA-OPERATION-NAME", "");
			// ebay_con.addRequestProperty("X-EBAY-SOA-SECURITY-TOKEN",
			// "text/xml");

			ebay_con.addRequestProperty("X-EBAY-API-COMPATIBILITY-LEVEL", "697");
			ebay_con.addRequestProperty("X-EBAY-API-DEV-NAME",
					"fd40c571-c3c5-455d-9ff1-82c284b29d80");
			ebay_con.addRequestProperty("X-EBAY-API-APP-NAME",
					"Carnegie-4827-41e3-8147-bb6e505fd31e");
			ebay_con.addRequestProperty("X-EBAY-API-CERT-NAME",
					"23ca5549-1e53-4540-accb-8bb2e878bc4b");
			ebay_con.addRequestProperty("X-EBAY-API-SITEID", "0"); // USA
			ebay_con.addRequestProperty("X-EBAY-API-CALL-NAME",
					template.substring(0, template.length() - 4));

			// Transform and write the Document to the stream
			ebay_con.setDoOutput(true);
			OutputStream out = ebay_con.getOutputStream();
			TransformerFactory tf = TransformerFactory.newInstance();
			Transformer tr = tf.newTransformer();
			Source input = new DOMSource(xmlDoc);
			Result output = new StreamResult(out);
			tr.transform(input, output);
			out.flush();
			out.close();

			// Get the Input stream for the response
			in = ebay_con.getInputStream();

			// Get the stream into a Document object

			Document response = docBuilder.parse(in);

			// close the input stream and ebay_con
			in.close();
				// return the response XML Document
			return response;

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public static void xmlSet(Document xml, String key, String value) {

	}

	public static String xmlGet(Document xml, String key) {
		String rs = xml.getElementsByTagName(key).item(0).getChildNodes()
				.item(0).getNodeValue();
		return rs;
	}
}
